//
//  YCAlertView.m
//  YCAlertViewDemo
//
//  Created by carpenter on 2019/11/7.
//  Copyright © 2019 carpenter. All rights reserved.
//

#import "YCAlertView.h"
#import <objc/runtime.h>

NS_INLINE CGFloat YCAlertContentViewWidth(){
    
    return [UIScreen mainScreen].bounds.size.width * 0.7;
}

NS_INLINE UIView * YCAlertCreateLineView(){
    
    UIView *lineView = [UIView new];
          
    lineView.backgroundColor = [UIColor alert_colorWithHex:@"#DFDFDF"];        // (223,223,223)
    
    return lineView;
}

typedef void(^YCAlertMaskTapBlock)(void);

typedef void(^YCAlertOperationControlDidClickBlock)(YCAlertAction * action);

static void * kYCAlertButtonConfigVoid = &kYCAlertButtonConfigVoid;

@interface UIButton (Config)

@property (nonatomic ,strong) YCAlertAction * action;

@end

@implementation UIButton (Config)

- (void)setAction:(YCAlertAction *)action{
    objc_setAssociatedObject(self, kYCAlertButtonConfigVoid, action, OBJC_ASSOCIATION_RETAIN_NONATOMIC);
}
-(YCAlertAction *)action{
  return objc_getAssociatedObject(self, kYCAlertButtonConfigVoid);
}

@end


@interface YCAlertContentTitleView : UIView

/// 初始化
-(instancetype)initWithTitle:(NSString *)title message:(NSString *)message config:(YCAlertConfig *)config;

@end

@interface YCAlertContentOperationView : UIView



/// 功能按钮点击回调
@property (nonatomic ,copy) YCAlertOperationControlDidClickBlock operationControlDidClickBlock;


-(instancetype)initWithConfig:(YCAlertConfig *)config;


/// 更新功能菜单视图
/// @param actionArray 菜单集合
-(void)reloadOperationView:(NSArray *)actionArray;

@end

@interface YCAlertBackgroundMaskView : UIView

/// 遮罩层点击回调
@property (nonatomic ,copy) YCAlertMaskTapBlock tapBlock;

@end




@interface YCAlertView ()


/// 背景遮罩
@property (nonatomic ,strong) YCAlertBackgroundMaskView * maskView;

/// 标题+描述
@property (nonatomic ,strong) YCAlertContentTitleView * titleView;

/// 功能按钮集合视图
@property (nonatomic ,strong) YCAlertContentOperationView * operationView;

/// 功能按钮集合
@property (nonatomic ,strong) NSMutableArray<YCAlertAction *> * actionArrayM;
 


/// 配置信息
@property (nonatomic ,strong) YCAlertConfig * config;

/// <#Description#>
@property (nonatomic ,copy) NSString * title;

/// <#Description#>
@property (nonatomic ,copy) NSString * message;

@end
 
/// 功能按钮高度
static CGFloat const kOperationViewItemHeight = 50.0;

/// 分割线宽度
static CGFloat const kAlertSegmentationLineWidth = 1.0;

@implementation YCAlertView

- (instancetype)initWithTitle:(NSString *)title message:(NSString *)message config:(YCAlertConfig *)config {
    if (self = [super init]) {

         // 防止类型不匹配或者为空
         if ((config == nil) || ([config isKindOfClass:[YCAlertConfig class]] == false)) {
              config = [YCAlertConfig new];
          }

         self.config = config;

        self.title = title;
        
        self.message = message;
        
        [self basicConfig];

     }

    return self;
}

-(void)basicConfig{
    
    self.backgroundColor = [UIColor whiteColor];
    self.layer.cornerRadius = self.config.cornersRadius;
    self.layer.masksToBounds = true;
    
    self.autoresizingMask = UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight;

    
    
    //遮罩视图
    self.maskView = [[YCAlertBackgroundMaskView alloc] initWithFrame:[UIScreen mainScreen].bounds];
    self.maskView.backgroundColor = [[UIColor blackColor] colorWithAlphaComponent:CGFLOAT_MIN];

    //‘标题+描述’视图
    self.titleView = [[YCAlertContentTitleView alloc] initWithTitle:self.title message:self.message config:self.config];

    //功能菜单视图
    self.operationView = [[YCAlertContentOperationView alloc] initWithConfig:self.config];

    //功能按钮点击事件监听
    __weak typeof(self) weakself = self;
    self.operationView.operationControlDidClickBlock = ^(YCAlertAction *action) {
        __strong typeof(self) strongself = weakself;

        if (action.completionHandle) {
             action.completionHandle();
         }
        
        [strongself dismiss];
    };

    //遮罩层点击监听
    self.maskView.tapBlock = ^{

        __strong typeof(self) strongself = weakself;

        if (strongself.config.touchHide == true) {

             [strongself dismiss];
         }
    };
}


 
//MARK: - PublicInterface

-(void)appendAction:(YCAlertAction *)action{
    
    //记录用户添加的功能,在展示的时候动态获取创建
    [self.actionArrayM addObject:action];
}

-(void)show{
 
//FIXME: - 防止未添加功能按钮无法移除
    if (self.actionArrayM.count == 0) {
        self.config.touchHide = true;
    }
      
    
    [self addSubview:self.titleView];
    [self addSubview:self.operationView];
    
    //根据用户添加的功能，动态创建contentView
    [self.operationView reloadOperationView:self.actionArrayM];
    
    
    self.titleView.frame = self.titleView.bounds;
    self.operationView.frame = CGRectMake(0, CGRectGetHeight(self.titleView.frame), YCAlertContentViewWidth(), CGRectGetHeight(self.operationView.frame));
    
    //是否加载中间分割线（titleView | operationView）
    if (self.actionArrayM.count > 0) {
        
        UIView *lineView = YCAlertCreateLineView();
        [self addSubview:lineView];
        lineView.frame = CGRectMake(0, CGRectGetHeight(self.titleView.frame), YCAlertContentViewWidth(), kAlertSegmentationLineWidth);
    }
    
  //先将遮罩添加到当前展示的window层
    UIWindow * window = [UIApplication sharedApplication].keyWindow;
    [window addSubview:self.maskView];
    [window bringSubviewToFront:self.maskView];
    
    //将整合好的展示视图添加到屏幕中心
    [self.maskView addSubview:self];
    
    CGSize mainScreenSize = [UIScreen mainScreen].bounds.size;
       
    CGFloat kContentViewHeight = CGRectGetHeight(self.titleView.frame) + CGRectGetHeight(self.operationView.frame);
     
    self.frame = CGRectMake((mainScreenSize.width - YCAlertContentViewWidth())/2.0, (mainScreenSize.height - kContentViewHeight)/2.0, YCAlertContentViewWidth(), kContentViewHeight);

    
    //动画
    self.transform = CGAffineTransformMakeScale(0.01f, 0.01f);//将要显示的view按照正常比例显示出来
    [UIView beginAnimations:nil context:UIGraphicsGetCurrentContext()];
    [UIView setAnimationCurve:UIViewAnimationCurveEaseInOut];//InOut 表示进入和出去时都启动动画
    [UIView setAnimationDuration:self.config.animationDuration];//动画时间
    self.transform = CGAffineTransformMakeScale(1.0f, 1.0f);//先让要显示的view最小直至消失
    [UIView commitAnimations];//启动动画
 
    
    [UIView animateWithDuration:self.config.animationDuration
                          delay:0
                        options:UIViewAnimationOptionCurveEaseIn|UIViewAnimationOptionCurveEaseOut
                     animations:^{

        self.maskView.backgroundColor = [[UIColor blackColor] colorWithAlphaComponent:self.config.maskAlpha];

    } completion:^(BOOL finished) {

    }];
    
}

-(void)dismiss{
    
    [UIView animateWithDuration:self.config.animationDuration delay:0 options:0 animations:^{

        self.maskView.alpha = CGFLOAT_MIN;
        
    } completion:^(BOOL finished) {
        
        [self.maskView removeFromSuperview];
    }];
}

//MARK: - Getter

-(NSMutableArray<YCAlertAction *> *)actionArrayM{
    if (!_actionArrayM) {
        _actionArrayM = [NSMutableArray array];
    }
    return _actionArrayM;
}


@end

 
@implementation YCAlertView (NormalAlert)

+(void)yc_showAlertWithTitle:(NSString *)title message:(NSString *)message isCancle:(BOOL)isCancle sureHandle:(void(^)(void))sureHandle cancleHandle:(void(^)(void))cancleHandle{
    
    YCAlertView * alert = [[YCAlertView alloc] initWithTitle:title message:message config:nil];
    
    if (isCancle) {
        
        [alert appendAction:[YCAlertAction actionWithTitle:@"取消" textColor:nil completionHandle:^{
              
               if (cancleHandle) {
                   cancleHandle();
               }
               
           }]];
    }
    
    [alert appendAction:[YCAlertAction actionWithTitle:@"确定" textColor:nil completionHandle:^{
       
        if (sureHandle) {
            sureHandle();
        }
        
    }]];
    
    [alert show];
}

@end

@interface YCAlertContentTitleView ()

/// 标题
@property (nonatomic ,strong) UILabel * titleLabel;

/// 描述标签
@property (nonatomic ,strong) UILabel * messageLabel;

@end

@implementation YCAlertContentTitleView{
 
    NSString * _title;
 
    NSString * _message;
    
    YCAlertConfig * _config;
}


-(instancetype)initWithTitle:(NSString *)title message:(NSString *)message config:(YCAlertConfig *)config{
    
    if (self = [super init]) {
        
        //保护层，防止标题和描述均为空
        if (title.length == 0 && message.length == 0)  {
            title = @"温馨提示";
        }
        
        _title = title;
        
        _message = message;
        
        _config = config;
        
        self.autoresizingMask = UIViewAutoresizingFlexibleWidth|UIViewAutoresizingFlexibleHeight;;
        
        [self setupTitleView];
        
    }
    return self;
}
-(void)setupTitleView{
    
    
    //边距
    UIEdgeInsets edgInset = UIEdgeInsetsMake(20.0, 20.0, 20.0, 20.0);
    
    //文本宽度
    CGFloat kTextWidth = YCAlertContentViewWidth() - edgInset.left - edgInset.right;
    
    //单文本高度
    CGFloat kSingleTitleMinHeight = kOperationViewItemHeight;
    
    //描述文本最大高度
    CGFloat kMessageTextMaxHeight = [UIScreen mainScreen].bounds.size.height * 0.5;
    
    //标题标签文本高度
    CGFloat kTitleLabelHeight = [self textHeightWithLabel:self.titleLabel width:kTextWidth];
    
    //描述标签文本高度
    CGFloat kMessageLabelHeight = [self textHeightWithLabel:self.messageLabel width:kTextWidth];
    
    if (_message.length == 0) {
       
        //只展示标题
        if (kTitleLabelHeight < kSingleTitleMinHeight) {
            kTitleLabelHeight = kSingleTitleMinHeight;
        }
        
        self.titleLabel.frame = CGRectMake(edgInset.left, edgInset.top, kTextWidth, kTitleLabelHeight);
             
        self.bounds = CGRectMake(0, 0, YCAlertContentViewWidth(), CGRectGetMaxY(self.titleLabel.frame) + edgInset.bottom);
        
    }else if(_title.length == 0){
                
        //只展示描述文本
        if (kMessageLabelHeight < kSingleTitleMinHeight) {
            kMessageLabelHeight = kSingleTitleMinHeight;
        }else if(kMessageLabelHeight > kMessageTextMaxHeight){
            kMessageLabelHeight = kMessageTextMaxHeight;
        }
        self.messageLabel.frame = CGRectMake(edgInset.left, edgInset.top, kTextWidth, kMessageLabelHeight);
              
        self.bounds = CGRectMake(0, 0, YCAlertContentViewWidth(), CGRectGetMaxY(self.messageLabel.frame) + edgInset.bottom);

    }else{
        //标题+描述文本
        
        //标题标签文本高度
        CGFloat kTitleLabelHeight = [self textHeightWithLabel:self.titleLabel width:kTextWidth];
        
        //描述标签文本高度
        CGFloat kMessageLabelHeight = [self textHeightWithLabel:self.messageLabel width:kTextWidth];
        if(kMessageLabelHeight > kMessageTextMaxHeight){
            kMessageLabelHeight = kMessageTextMaxHeight;
        }
        self.titleLabel.frame = CGRectMake(edgInset.left, edgInset.top, kTextWidth, kTitleLabelHeight);
        
        self.messageLabel.frame = CGRectMake(edgInset.left, CGRectGetMaxY(self.titleLabel.frame) + 20, kTextWidth, kMessageLabelHeight);
        
        self.bounds = CGRectMake(0, 0, YCAlertContentViewWidth(), CGRectGetMaxY(self.messageLabel.frame) + edgInset.bottom);
        
    }
 
}

-(CGFloat )textHeightWithLabel:(UILabel *)label width:(CGFloat)width{
     
    if (label.text.length == 0) {
        label.hidden = true;
        return 0.0;
    }
    
    CGRect rect = [label.text boundingRectWithSize:CGSizeMake(width, CGFLOAT_MAX)
                                           options:NSStringDrawingTruncatesLastVisibleLine | NSStringDrawingUsesLineFragmentOrigin | NSStringDrawingUsesFontLeading
                                        attributes:@{NSFontAttributeName : label.font}
                                           context:nil];
    
    CGFloat height = rect.size.height;
  
    return height;
}

- (UILabel *)titleLabel {
    if (!_titleLabel) {
         _titleLabel = [UILabel new];
         _titleLabel.textAlignment = NSTextAlignmentCenter;
         _titleLabel.textColor = _config.titleColor;
         _titleLabel.font = _config.titleFont;
         _titleLabel.text = _title;
         [self addSubview:_titleLabel];
     }

    return _titleLabel;
}
-(UILabel *)messageLabel{
    if (!_messageLabel) {
        _messageLabel = [UILabel new];
        _messageLabel.textAlignment = NSTextAlignmentCenter;
        _messageLabel.textColor = _config.messageColor;
        _messageLabel.font = _config.messageFont;
        _messageLabel.text = _message;
        _messageLabel.numberOfLines = 0;
        [self addSubview:_messageLabel];
    }
    return _messageLabel;
}

@end


@implementation YCAlertContentOperationView{
    
    YCAlertConfig * _config;
}


-(void)actionButtonClick:(UIButton *)sender{
    
    if (self.operationControlDidClickBlock) {
        self.operationControlDidClickBlock(sender.action);
    }
    
}

- (instancetype)initWithConfig:(YCAlertConfig *)config{
    
    if (self = [super init]) {
        
        _config = config;
        
        self.autoresizingMask = UIViewAutoresizingFlexibleWidth|UIViewAutoresizingFlexibleHeight;;
        
    }
    return self;
}
- (void)reloadOperationView:(NSArray *)actionArray {

    // 是否需要水平排列(2个按钮时水平排列)
    BOOL isHorizontal = (actionArray.count == 2);

    // 单个按钮宽度
    CGFloat kOperationItemWidth = isHorizontal ? YCAlertContentViewWidth() / 2.0 :  YCAlertContentViewWidth();

    // 动态创建功能按钮
    for (NSInteger index = 0; index < actionArray.count; index++) {

         UIButton *button = [self createActionButton:actionArray[index]];

         [button addTarget:self action:@selector(actionButtonClick:) forControlEvents:UIControlEventTouchUpInside];

         if (isHorizontal) {

              button.frame = CGRectMake(index * kOperationItemWidth, 0, kOperationItemWidth, kOperationViewItemHeight);

             //左右两个按钮间分割线
              if (index == 1) {
                   UIView *lineView = YCAlertCreateLineView();
                   [button addSubview:lineView];
                   lineView.frame = CGRectMake(0, 0, kAlertSegmentationLineWidth, kOperationItemWidth);
               }
          } else {


              button.frame = CGRectMake(0, index * kOperationViewItemHeight, kOperationItemWidth, kOperationViewItemHeight);;

              //上下按钮间分割线
              UIView *lineView = YCAlertCreateLineView();
              [button addSubview:lineView];
              lineView.frame = CGRectMake(0, kOperationViewItemHeight - kAlertSegmentationLineWidth, kOperationItemWidth, kAlertSegmentationLineWidth);
          }

         [self addSubview:button];
     }
    
    // 动态获取视图高度
    CGFloat kOperationViewHeight = kOperationViewItemHeight * actionArray.count;

    if (isHorizontal) {
        
         kOperationViewHeight = kOperationViewHeight - kOperationViewItemHeight;
     }

    self.bounds = CGRectMake(0, 0, YCAlertContentViewWidth(), kOperationViewHeight);
}

//MARK: - Getter
-(UIButton *)createActionButton:(YCAlertAction *)action{
    
    UIButton * button = [UIButton buttonWithType:UIButtonTypeCustom];
    
    [button setTitle:action.title forState:UIControlStateNormal];
    
    button.action = action;
    
    if (action.textColor) {
        
        [button setTitleColor:action.textColor forState:UIControlStateNormal];
        
    }else{
        
        [button setTitleColor:_config.actionTextColor forState:UIControlStateNormal];
    }
    
    
    if (action.textFont) {
        
        button.titleLabel.font = action.textFont;
        
    }else{
        
        button.titleLabel.font = _config.actionTextFont;
    }
    
    
    if (action.backgroundNormalColor) {
        
        [button setBackgroundImage:[UIImage alert_imageWithColor:action.backgroundNormalColor] forState:UIControlStateNormal];
    }else {
        
        [button setBackgroundImage:[UIImage alert_imageWithColor:_config.actionBackgroundNormalColor] forState:UIControlStateNormal];
    }
    
    
    if (action.backgroundHeightColor) {
        
        [button setBackgroundImage:[UIImage alert_imageWithColor:action.backgroundHeightColor] forState:UIControlStateHighlighted];
    }else{
        
        [button setBackgroundImage:[UIImage alert_imageWithColor:_config.actionBackgroundHeightColor] forState:UIControlStateHighlighted];
    }
    
    
    return button;
}


@end



@implementation YCAlertBackgroundMaskView

- (instancetype)initWithFrame:(CGRect)frame
{
    self = [super initWithFrame:frame];
    if (self) {
        
        UIView * backgroundTapView = [[UIView alloc] initWithFrame:frame];
        [self addSubview:backgroundTapView];
        
        UITapGestureRecognizer * tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(maskViewTap)];
             
        [backgroundTapView addGestureRecognizer:tap];
        
    }
    return self;
}

-(void)maskViewTap{
    if (self.tapBlock) {
        self.tapBlock();
    }
}

@end
